package com.lianke.app.phpsharer;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;

import com.lianke.app.phpsharer.cache.ConfigCache;
import com.lianke.app.phpsharer.category.CategoryTabActivity;
import com.lianke.app.phpsharer.digest.DigestTabActivity;
import com.lianke.app.phpsharer.favorite.FavoriteTabActivity;
import com.lianke.app.phpsharer.infomation.InfomationTabActivity;
import com.lianke.app.phpsharer.setting.SettingTabActivity;
import com.tianxia.lib.baseworld.BaseApplication;
import com.tianxia.lib.baseworld.R;
import com.tianxia.lib.baseworld.sync.http.AsyncHttpClient;
import com.tianxia.lib.baseworld.sync.http.AsyncHttpResponseHandler;
import com.tianxia.lib.baseworld.utils.NetworkUtils;
import com.tianxia.lib.baseworld.utils.PreferencesUtils;

public class AppApplication extends BaseApplication {

	
	public static final String DOMAIN = "domain";	
	public static final String DOMAIN_URL = "url";
	// 内存卡的路径
	public static String mSdcardDataDir;
	
	//远程路径
	public static String mDomain = "http://192.168.1.114/android/"; 

	//public static String lujing = "/phpsharer/config/";
	
	public static String mBakeDomain = "http://192.168.1.114/android/";
	
	public static String mApkDownloadUrl = null;
	
	/* (non-Javadoc) 填充activity
	 * @see com.tianxia.lib.baseworld.BaseApplication#fillTabs()
	 */
	@Override
	public void fillTabs() {
		// TODO Auto-generated method stub
		mTabActivitys.add(InfomationTabActivity.class);
		mTabActivitys.add(CategoryTabActivity.class);
		mTabActivitys.add(DigestTabActivity.class);
		mTabActivitys.add(FavoriteTabActivity.class);
		mTabActivitys.add(SettingTabActivity.class);

		mTabNormalImages.add(R.drawable.infomation_normal);
		mTabNormalImages.add(R.drawable.category_normal);
		mTabNormalImages.add(R.drawable.digest_normal);
		mTabNormalImages.add(R.drawable.favorite_normal);
		mTabNormalImages.add(R.drawable.setting_normal);

		mTabPressImages.add(R.drawable.infomation_press);
		mTabPressImages.add(R.drawable.category_press);
		mTabPressImages.add(R.drawable.digest_press);
		mTabPressImages.add(R.drawable.favorite_press);
		mTabPressImages.add(R.drawable.setting_press);
	}

	/* (non-Javadoc)初始化数据库
	 * @see com.tianxia.lib.baseworld.BaseApplication#initDb()
	 */
	@Override
	public void initDb() {
		// TODO Auto-generated method stub

	}

	@Override
	public void initEnv() {
		mAppName = "phpsharer";
		mDownloadPath = "/phpsharer/download";
		// TODO Auto-generated method stub
		//创建文件夹
		if (Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			File file = new File(Environment.getExternalStorageDirectory()
					.getPath() + "/phpsharer/config/");
			if (!file.exists()) {
				if (file.mkdirs()) {
					mSdcardDataDir = file.getAbsolutePath();
				}
			} else {
				mSdcardDataDir = file.getAbsolutePath();
			}
		}
		//获取网络状态
		mNetWorkState = NetworkUtils.getNetworkState(this);
		
		//检查domain
		//checkDomain(mDomain, false);
		
		//AppConnect.getInstance(getApplicationContext());
	}
	
	
	public void checkDomain(final String domain, final boolean stop){
        AppApplication.mDomain = PreferencesUtils.getStringPreference(getApplicationContext(), DOMAIN, DOMAIN_URL, mDomain);
        String cacheConfigString = ConfigCache.getUrlCache(domain + "host.php");
        if (cacheConfigString != null) {
        	//System.out.println("host.php已存在从缓存中加载");
            updateDomain(cacheConfigString);
        } else {
        	//远程加载
        	//System.out.println("checkDomain->远程加载host.php");
            AsyncHttpClient client = new AsyncHttpClient();
            client.get(domain + "host.php", new AsyncHttpResponseHandler(){

                @Override
                public void onStart() {
                	
                }

                @Override
                public void onSuccess(String result) {
                	//System.out.println("加载成功");
                    ConfigCache.setUrlCache(result, domain + "host.php");
                    updateDomain(result);
                }

                @Override
                public void onFailure(Throwable arg0) {
                    if (!stop) {
                        checkDomain(mBakeDomain, true);
                    }
                }

                @Override
                public void onFinish() {
                }
            });
        }
    }
	
	public void updateDomain(String result) {
        try {
            JSONObject appreciateConfig = new JSONObject(result);
            String domain = appreciateConfig.optString("domain");
            if (domain != null && !"".equals(domain)) {
                AppApplication.mDomain = domain;
                PreferencesUtils.setStringPreferences(getApplicationContext(), DOMAIN, DOMAIN_URL, domain);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

	/* (non-Javadoc)退出程序
	 * @see com.tianxia.lib.baseworld.BaseApplication#exitApp(android.content.Context)
	 */
	@Override
	public void exitApp(Context context) {
		// TODO Auto-generated method stub
		AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder.setTitle(this.getString(R.string.app_exit_title))
            .setMessage(this.getString(R.string.app_exit_message))
            .setPositiveButton("退出",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //AppConnect.getInstance(context).finalize();
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }
            ).setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }
            );
        alertBuilder.create().show();
	}

}
